package com.eonmind.vip.task;

import com.eonmind.common.contract.timer.Timer;
import com.eonmind.common.provider.entity.vip.VipPackage;
import com.eonmind.common.provider.entity.vip.Subscription;
import com.eonmind.common.provider.entity.vip.UserWelfare;
import com.eonmind.vip.mapper.VipPackageMapper;
import com.eonmind.vip.mapper.SubscriptionMapper;
import com.eonmind.vip.mapper.UserWelfareMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;

/**
 * 每日任务：检查并处理过期订阅
 */
@Component
public class UpdateUserWelfareTask {

    @Autowired
    private UserWelfareMapper userWelfareMapper;

    @Autowired
    private SubscriptionMapper subscriptionMapper;

    @Autowired
    private VipPackageMapper vipPackageMapper;

    @Scheduled(cron = "0 0 0 * * ?") // 每天凌晨执行
    public void checkExpiredUpdateWelfare() {
        long currentTimestamp = Timer.currentTimestamp();
        List<Subscription> expireList = subscriptionMapper.findByStatusAndEndDateBefore("active", currentTimestamp);
        expireList.forEach((subscription -> {
            subscription.setStatus("expired")
                    .setUpdateTime(Timer.currentTimestamp());
            UserWelfare userWelfare = userWelfareMapper.getUserPlanByUserID(subscription.getUserId());
            userWelfare.getActiveSubscriptionIds().remove(subscription.getPlanId());
            userWelfareMapper.save(userWelfare);
            updateUserWelfareByActive(userWelfare.getUserId());
        }));
        subscriptionMapper.saveAllSub(expireList);

        // TODO 提醒用户会员过期
    }

    public void updateUserWelfareByActive(Long userId) {
        UserWelfare userWelfare = userWelfareMapper.getUserPlanByUserID(userId);
        List<Long> activePlanList = userWelfare.getActiveSubscriptionIds();
        List<VipPackage> vipPackages = vipPackageMapper.getPlanByIds(activePlanList);
        int dailyPoints = 0;
        HashSet<String> featureSet = new HashSet<>();
        for (VipPackage vipPackage : vipPackages) {
            dailyPoints += vipPackage.getDailyCoins();
            featureSet.addAll(vipPackage.getFeatures());
        }
        UserWelfare.CachedFeatures.Features features = new UserWelfare.CachedFeatures.Features();
        UserWelfare.CachedFeatures cachedFeatures = new UserWelfare.CachedFeatures()
                .setDailyCoins(dailyPoints)
                .setFeatures(features);
        UserWelfare userWelfare1 = new UserWelfare()
                .setUpdateTime(Timer.currentTimestamp())
                .setCachedFeatures(cachedFeatures);
        Boolean res = userWelfareMapper.updateUserPlanByUserID(userId, userWelfare1);
    }
}
